package com.neteast.androidclient.db;

import java.util.HashMap;
import java.util.Map;
import com.neteast.androidclient.contact.util.LoginUtil;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class GroupDao {
	private MyDBHelp dbHelp;
	private SQLiteDatabase db;
	private Context context;
	
	public GroupDao(Context context) {
		this.context=context;
	}
	
	public void open() {
		dbHelp=new MyDBHelp(context);
		db=dbHelp.getWritableDatabase();
	}
	
	public void close() {
		dbHelp.close();
	}
	/**
	 * 将系统通讯录的分组导入本应用的通讯录分组
	 * @param groups
	 * @return 系统通讯录的组id与本地分组id的映射关系
	 */
	public HashMap<String, String> importSysGroups(HashMap<String, String> groups) {
		if (groups==null||groups.size()==0) {
			return null;
		}
		HashMap<String, String> groupIdMapping=new HashMap<String, String>();
		for (Map.Entry<String, String> entry : groups.entrySet()) {
			String sysGid = entry.getKey();
			String groupName = entry.getValue();
			groupIdMapping.put(sysGid, insert(groupName));
		}
		return groupIdMapping;
	}
	
	public String insert(String groupName) {
		ContentValues values=new ContentValues();
		values.put("accountId", LoginUtil.getLastLoginUserId(context));
		values.put("title", groupName);
		return Long.toString(db.insert("groups", null, values));
	}
	
	public void update(String groupId,String groupName) {
		ContentValues values=new ContentValues();
		values.put("title", groupName);
		db.update("groups", values, "_id=? ", new String[]{groupId});
	}
	
	public void delete(String groupId) {
		db.delete("groups", "_id=? ", new String[]{groupId});
	}
	
	public String get(String groupId) {
		Cursor cursor = db.query("groups", new String[]{"title"}, "accountId=? AND _id=? ",
				new String[]{LoginUtil.getLastLoginUserId(context),groupId}, null, null, null);
		String gName=null;
		if (cursor.moveToFirst()) {
			gName = cursor.getString(0);
			cursor.close();
		}
		return gName;
	}
	/**
	 * 得到当前登录用户的所有分组
	 * 返回一个hashMap key是分组名，value为分组id
	 * @return
	 */
	public HashMap<String, String> getAll() {
		Cursor cursor = db.query("groups", new String[]{"_id","title"}, "accountId=?",
				new String[]{LoginUtil.getLastLoginUserId(context)}, null, null, null);
		HashMap<String, String> map=null;
		if (cursor.moveToFirst()) {
			map=new HashMap<String, String>();
			do {
				map.put(cursor.getString(1), cursor.getString(0));
			} while (cursor.moveToNext());
			cursor.close();
		}
		return map;
	}
}
